<?php
namespace Gigasweb\Forms;
class Tracker {

	var $_url = null;
	var $_postdata = null;

	function formTracker($url,$data = null)
	{
		$this->_url = $url;
		if($data && is_array($data)) {
			$this->_postdata = $data;
		} else {
			$this->_postdata = $_POST;
		}
	}

	function sendData()
	{
		if(!$this->_url || !$this->_postdata) return;

		$post = $this->buildPostData();

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$this->_url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 190);
		$result = curl_exec($ch);
		curl_close($ch);
		if ($result) return true;
		return false;
	}

	private function buildPostData()
	{
		$return = array();
		$ftr_ok = false;
		foreach($this->_postdata as $var => $value) {
			$return[] = $var.'='.urlencode(trim(stripslashes($value)));
			if($var == 'ftr_url') $ftr_ok = true;
		}
		if(!$ftr_ok) $return[] = 'ftr_url='.urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
		return implode('&',$return);
	}
}